package work.chenbo.spring_boot_shiro.modules.base.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import work.chenbo.spring_boot_shiro.common.util.CodecUtils;
import work.chenbo.spring_boot_shiro.common.vo.ResponseObject;
import work.chenbo.spring_boot_shiro.modules.sys_user.entity.SysUser;

/**
 * @author ChenBo
 * @className LoginController
 * @date 2019/10/28
 */
@Controller
@Slf4j
public class LoginController {


    @RequestMapping("/login")
    public String login(){
        return "auth/login";
    }


    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public @ResponseBody Object login(SysUser sysUser){

        if(StringUtils.isBlank(sysUser.getUserName())){
            return ResponseObject.fail();
        }
        String password =sysUser.getPassword();
        if (StringUtils.isBlank(password)){
            return ResponseObject.fail();
        }else {
            password = CodecUtils.decodeBase64(password);
        }

        try{
            UsernamePasswordToken token = new UsernamePasswordToken(sysUser.getUserName(),password);
            SecurityUtils.getSubject().login(token);
        }catch (Exception e){
            log.error(e.toString());
            return ResponseObject.fail();
        }
        return ResponseObject.success();
    }
}
